package store

import (
	"gitee.com/zaiqiang231/lovesport-user-service/app/model"
	"gorm.io/gorm"
)

type UserStore struct {
	db *gorm.DB
}

func (receiver UserStore) Execute(runnable Runnable) {
	runnable(receiver.db)
}

func (u *UserStore) Create(user *model.User) error {
	err := u.db.
		Create(&user).Error
	if err != nil {
		return err
	}
	return nil
}

func (u *UserStore) Update(user *model.User) error {
	err := u.db.
		Save(&user).Error
	if err != nil {
		return err
	}
	return nil
}

func (u *UserStore) Delete(id uint, isSoftDelete bool) error {
	user := &model.User{}
	var err error
	if isSoftDelete {
		err = u.db.
			Where("id = ?", id).
			Delete(&user).Error
	} else {
		err = u.db.
			Where("id = ?", id).
			Unscoped().
			Delete(&user).Error
	}

	if err != nil {
		return err
	}
	return nil
}

func (u *UserStore) Get(username string) (*model.User, error) {
	user := &model.User{}
	err := u.db.
		Where("name = ?", username).
		Preload("Authority").
		Preload("Authorities").
		First(&user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}
